package com.coolgor.coldot.service.auth.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.coolgor.coldot.enums.auth.LocalUserOperationStateEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.coolgor.coldot.dao.auth.LocalUserDao;
import com.coolgor.coldot.dto.auth.LocalUserExecution;
import com.coolgor.coldot.entity.auth.LocalUser;
import com.coolgor.coldot.exceptions.auth.LocalUserOperationException;
import com.coolgor.coldot.service.auth.LocalUserService;
import com.coolgor.coldot.common.PageCalculator;



@Service
public class LocalUserServiceImpl implements LocalUserService {
	private static Logger log = LoggerFactory.getLogger(LocalUserServiceImpl.class);
	
	@Autowired
	private LocalUserDao localUserDao;
	
	@Override
	public LocalUser getLocalUser(long userID) {
		return localUserDao.queryLocalUserById(userID);
	}	
	
	@Override
	public LocalUser getLocalUser(String username) {
		return localUserDao.queryLocalUserByUsername(username);
	}

	@Override
	public LocalUserExecution getLocalUserList(LocalUser localUserCondition, int pageIndex, int pageSize) {
		//将页码转换成行码
		int rowIndex = PageCalculator.calculateRowIndex(pageIndex, pageSize);
		//依据查询条件，调用dao层返回相关的查询结果列表
		List<LocalUser> localUserList = localUserDao.queryLocalUserList(localUserCondition, rowIndex, pageSize);
		//依据相同的查询条件，返回查询结果总数
		int count = localUserDao.queryLocalUserCount(localUserCondition);
		LocalUserExecution result = new LocalUserExecution();
		if (localUserList != null) {
			result.setState(LocalUserOperationStateEnum.SUCCESS.getState());
			result.setStateInfo(LocalUserOperationStateEnum.SUCCESS.getStateInfo());
			result.setLocalUserList(localUserList);
			result.setCount(count);
		} else {
			result.setState(LocalUserOperationStateEnum.INNER_ERROR.getState());
		}
		return result;
	}

	@Override
	@Transactional
	public LocalUserExecution addLocalUser(LocalUser localUser) throws LocalUserOperationException {
		// 空值判断
		if (localUser == null) {
			return new LocalUserExecution(LocalUserOperationStateEnum.NULL_USER);
		}
		int effectedNum;
		try {
			// 数据库中是否有相同username
			LocalUser checkusername = new LocalUser();
			checkusername.setUsername(localUser.getUsername());
			effectedNum = localUserDao.queryLocalUserCount(checkusername);
			if (effectedNum > 0) {
				return new LocalUserExecution(LocalUserOperationStateEnum.EXISTUSERNAME);
			} 
			// 赋初始值
			localUser.setCreateTime(new Date());
			localUser.setLastEditTime(new Date());
			// 添加
			effectedNum = localUserDao.insertLocalUser(localUser);
			if (effectedNum <= 0) {
				throw new LocalUserOperationException("本地用户创建失败");
			} 
		} catch (Exception e) {
			throw new LocalUserOperationException("addLocalUser error:" + e.getMessage());
		}
		return new LocalUserExecution(LocalUserOperationStateEnum.SUCCESS, localUser);
	}

	@Override
	@Transactional
	public LocalUserExecution modifyLocalUser(LocalUser localUser) throws LocalUserOperationException {
		// 空值判断
		if (localUser == null) {
			return new LocalUserExecution(LocalUserOperationStateEnum.NULL_USER);
		}
		int effectedNum;
		// 判断是否有更改用户名
		// 如果更改了用户名，则判断新的用户名是否有存在
		LocalUser checkUser = localUserDao.queryLocalUserById(localUser.getUserID());
		if ( null == checkUser ) {
			//判断这个ID下是否有用户，如果没有则返回空用户状态
			return new LocalUserExecution(LocalUserOperationStateEnum.NULL_USER);
		}
		if (localUser.getUsername()!=null && !checkUser.getUsername().equals(localUser.getUsername())) {
			//如果ID下有用户，则判断该用户是否跟新的User相同
			//如果新旧用户名不一致，则进入数据库查询新用户名是否已经被使用
			LocalUser checkUserName = new LocalUser();
			checkUserName.setUsername(localUser.getUsername());
			effectedNum = localUserDao.queryLocalUserCount(checkUserName);
			if (effectedNum > 0) {
				// 如果数据库中已经存在这个username，则反馈用户名已存在
				return new LocalUserExecution(LocalUserOperationStateEnum.EXISTUSERNAME);
			} 
		}
		// 即将更新用户信息
		try {
			// 赋初始值
			localUser.setLastEditTime(new Date());
			// 更新操作
			effectedNum = localUserDao.updateLocalUser(localUser);
			if (effectedNum <= 0) {
				throw new LocalUserOperationException("本地用户更新失败");
			} 
		} catch (Exception e) {
			throw new LocalUserOperationException("Modify LocalUser error:" + e.getMessage());
		}
		return new LocalUserExecution(LocalUserOperationStateEnum.SUCCESS, localUser);
	}

	@Override
	@Transactional
	public LocalUserExecution removeLocalUser(LocalUser localUser) throws LocalUserOperationException {
		// 空值判断
		if (localUser == null) {
			return new LocalUserExecution(LocalUserOperationStateEnum.NULL_USER);
		}
		int effectedNum;
		try {
			// 执行删除操作
			effectedNum = localUserDao.deleteLocalUser(localUser);
			if (effectedNum <= 0) {
				throw new LocalUserOperationException("本地用户删除失败");
			} 
		} catch (Exception e) {
			throw new LocalUserOperationException("Delete LocalUser error:" + e.getMessage());
		}
		return new LocalUserExecution(LocalUserOperationStateEnum.SUCCESS, localUser);
	}

	@Override
	@Transactional
	public LocalUserExecution batchRemoveLocalUser(List<LocalUser> localUserList) throws LocalUserOperationException {
		// 空值判断
		if (localUserList == null) {
			return new LocalUserExecution(LocalUserOperationStateEnum.NULL_USER);
		}
		List<Long> localUserIDList = new ArrayList<Long>();
		for (int i=0; i<localUserList.size(); i++) {
			localUserIDList.add(localUserList.get(i).getUserID());			
		}
		int effectedNum;
		try {
			// 执行删除操作
			effectedNum = localUserDao.batchDeleteLocalUser(localUserIDList);
			if (effectedNum <= 0) {
				throw new LocalUserOperationException("本地用户批量删除失败");
			} 
		} catch (Exception e) {
			throw new LocalUserOperationException("Delete LocalUser error:" + e.getMessage());
		}
		LocalUserExecution ue = new LocalUserExecution(LocalUserOperationStateEnum.SUCCESS);
		//将删除的记录总数加入到返回值
		ue.setCount(effectedNum);
		return ue;
	}

}
